# -*- coding: utf-8 -*-
from config.celery_config import celery_app
import datetime
import json
import os
from utils.import_cards_data import import_cards
from utils.import_product_imgs_data import import_product_imgs
from controls import data_city_base_mysql
from controls import data_city_map_mysql
from controls import data_product_desc_mongo
from controls import data_card_info_mongo
from utils import file_util
from utils import log
from config import etc
from utils.util import get_utf8_str


@celery_app.task
def update_all(cityid):
    try:
        if not cityid:
            log.w('params fetching error')
            res = {'idx': 0, 'ret': 0, 'msg': '请选择城市', 'res': []}
            return res

        city_base = data_city_base_mysql.get_city_base_by_id(int(cityid))
        city_base_path = 'import_city/city_%s_%s' % (cityid, city_base['name'])
        # map csb
        csbfile_res = file_util.local_file_upload(
            city_base_path,
            city_base['name'] + '.csb',
            cityid
        )
        # map jpg
        jpgfile_res = file_util.local_file_upload(
            city_base_path,
            city_base['name'] + 'map.jpg',
            cityid
        )
        # map png
        pngfile_res = file_util.local_file_upload(
            city_base_path,
            city_base['name'] + '.png',
            cityid
        )
        # map plist
        plistfile_res = file_util.local_file_upload(
            city_base_path,
            city_base['name'] + '.plist',
            cityid
        )
        # city ball
        iconfile_res = file_util.local_file_upload(
            city_base_path,
            'city_ball_' + city_base['name'] + '.png',
            cityid
        )
        # 景点信息json
        jsonfile_res = file_util.local_file_upload(
            city_base_path,
            'city_' + cityid + '.json',
            cityid
        )

        error = False
        res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
        if not csbfile_res:
            error = True
            res['res'].append('csbfile upload failure.')
        if not jpgfile_res:
            error = True
            res['res'].append('jpgfile upload failure.')
        if not pngfile_res:
            error = True
            res['res'].append('pngfile upload failure.')
        if not plistfile_res:
            error = True
            res['res'].append('plistfile upload failure.')
        if not iconfile_res:
            error = True
            res['res'].append('iconfile upload failure.')
        if not jsonfile_res:
            error = True
            res['res'].append('jsonfile upload failure.')

        if error:
            log.e(res)
            return res

        city_map_dict = data_city_map_mysql.get_city_map_by_cityid(int(cityid) )
        log.i(city_map_dict)

        map_item = {}
        version = 1
        if city_map_dict:
            map_item = city_map_dict
            del map_item['id']
            version += map_item['version']

        map_item['cityid'] = int(cityid)
        map_item['version'] = version
        map_item['ctime'] = datetime.datetime.now()

        if csbfile_res:
            map_item['csbfile'] = 'http://static.shitouren.com/group'+str(csbfile_res['group'])+'/'+csbfile_res['path']+'.'+csbfile_res['ext']
        if jpgfile_res:
            map_item['jpgfile'] = 'http://static.shitouren.com/group'+str(jpgfile_res['group'])+'/'+jpgfile_res['path']+'.'+jpgfile_res['ext']
        if pngfile_res:
            map_item['pngfile'] = 'http://static.shitouren.com/group'+str(pngfile_res['group'])+'/'+pngfile_res['path']+'.'+pngfile_res['ext']
        if plistfile_res:
            map_item['plistfile'] = 'http://static.shitouren.com/group'+str(plistfile_res['group'])+'/'+plistfile_res['path']+'.'+plistfile_res['ext']
        if iconfile_res:
            map_item['iconfile'] = 'http://static.shitouren.com/group'+str(iconfile_res['group'])+'/'+iconfile_res['path']+'.'+iconfile_res['ext']
        if jsonfile_res:
            map_item['jsonfile'] = 'http://static.shitouren.com/group'+str(jsonfile_res['group'])+'/'+jsonfile_res['path']+'.'+jsonfile_res['ext']

        log.i(map_item)

        update_res = data_city_map_mysql.add_city_map_item(map_item)
        if not update_res:
            res['res'].append('add city map error. cityid:' + cityid)
            log.e(res)
            return res

        update_res = data_city_base_mysql.update_city_version_by_cityid( int(cityid), p_version=version )
        if not update_res :
            res['res'].append('update city_base version error. cityid:' + cityid)
            log.e(res)
            return res

        # techan product
        try:
            with open(os.path.join(etc.path_seafile_root, 'import_shop/techan_%s.json' % cityid), 'r') as pfp:
                product_jsonfile = pfp.read()
        except:
            product_jsonfile = None

        if not product_jsonfile:
            log.w('params fetching error')
            res = {'idx': 0, 'ret': 2, 'msg': '特产Json文件没有上传', 'res': []}
            return res

        product_json_dict = json.loads(get_utf8_str(product_jsonfile))

        res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
        if int(cityid) != int(product_json_dict['cityid']):
            res['res'].append('this product json file content dont match selected cityid.')
            return res

        # update to mongodb
        data_product_desc_mongo.update_city_product( cityid, product_json_dict['products'] )

        # city card
        try:
            with open(os.path.join(etc.path_seafile_root, 'import_card/city_cards_%s.json' % cityid), 'r') as pfp:
                card_jsonfile = pfp.read()
        except:
            card_jsonfile = None

        if not card_jsonfile:
            log.w('city card json error')
            res = {'idx': 0, 'ret': 1, 'msg': 'please input this city\'s cards Json file.', 'res':[] }
            return res

        # 把文件内容读入，存入到mongodb
        #exec("json_dict="+jsonfile['body'])
        card_json_dict = json.loads(get_utf8_str(card_jsonfile))

        res = {'idx':0, 'ret':1, 'msg':'ng', 'res': []}
        if int(cityid) != int(card_json_dict['cityid']):
            res['msg'] = 'this city card json file content dont match selected cityid.'
            return res

        # update to mongodb
        data_card_info_mongo.update_city_card(cityid, card_json_dict['cards'])

        import_cards(
            os.path.join(
                etc.path_seafile_root,
                'import_card/city_%.3d_card_img/city%s_card_imgs.json'
                % (int(cityid), cityid)
            ),
            os.path.join(
                etc.path_seafile_root,
                'import_card/city_%.3d_card_img' % int(cityid)
            )
        )

        import_product_imgs(
            os.path.join(
                etc.path_seafile_root,
                'import_shop/city_%.3d_img/city%s_imgs.json'
                % (int(cityid), cityid)
            ),
            os.path.join(
                etc.path_seafile_root,
                'import_shop/city_%.3d_img/' % int(cityid)
            )
        )

        res['msg'] = "update city's all info success. cityid:" + str(cityid)
        res['ret'] = 0
        return res
    except Exception, e:
        log.w('something error')
        res = {'idx': 0, 'ret': 1, 'msg': str(e), 'res': []}
        return res
